""" convert an rst docstring into html """

import os
from collections import namedtuple
# import stuff from ourselves:
from . epydoc_modules.markup.restructuredtext import parse_docstring

DocstrHTML = namedtuple('DocstrHTML', ('summary', 'body', 'fields'))

def convert_docstr(docstr, linker):
    """ convert an rst docstr into html, including fields

        fields are always treated as flat, even when they look nested
        this is an epydoc parser limitation
    """
    
    if docstr == '' or docstr is None:
        return DocstrHTML('', '', '')
    else:
        parsed_docstr = parse_docstring(docstr, [])
        
        # convert the summary to html:
        summary, has_more = parsed_docstr.summary()
        summary_html = summary.to_html(linker)
        
        # convert the body to html:
        body, fields = parsed_docstr.split_fields()
        ## May have to handle body being None here
        body_html = body.to_html(linker)
        
        # process the fields, bodies to html:
        fields_html = [] # list of strings, giving html for each template
        f = None
        while fields:
            #print 'fields:', fields
            lasttag = '' if f is None else f.tag()  
            
            # get info for this field:
            f = fields.pop(0)
            fieldvals = {'field_tag':f.tag(),
                         'field_arg':f.arg() or '',  # might be None
                         'field_body':f.body().to_html(linker),
                         'param_type':''} # what we pass to the template
            
            # Combine a 'type' field which immediately follows a 'param' field:
            if len(fields) > 0:
                if fields[0].tag() == 'type' and fields[0].arg() == f.arg(): # is a type field with a matching param-name
                    #print 'have matching type field'
                    type_f = fields.pop(0)
                    fieldvals['type_info'] = type_f.body().to_html(linker)
                    del fieldvals['param_type'] # forces use of the 'param_type' template instead
            
            fields_html.append(fieldvals)
                
        return DocstrHTML(summary_html, body_html, fields_html)